const app = getApp()

import { requestApi } from '../../../api';
import { logUpload } from '../../../utils/logUpload';
import { dateFormat } from '../../../utils/dateFormat';
import { formatImage } from '../../../utils/formatImage';

Page({
    data: {
        tId: '',
        total: 0,
        info: null,
        nav: null,
        goodsList: null,
        cur: 0,
        nId: 0,
        scrollId: '',
        scrollLeft: 0,
        scrollList: [],
        scrollTop: 0,
        winW: wx.getSystemInfoSync().windowWidth,
        winH: wx.getSystemInfoSync().windowHeight,
        h: 0,
        navTop: 0,
        groupInfo: null,  // 拼团信息
        isShowBackTop: false,
        discount_time: '',
    },
    onLoad(options) {
        let scene = '';
        let paramArr = [];
        let channel = '';
        let tid = '';
        let utm_source = '';
        let utm_share = '';
        let utm_medium = '';
        let utm_campaign = '';
        
        if (options.scene && options.scene.length) {
            scene = decodeURIComponent(options.scene);
            paramArr = scene.split(',');

            if (paramArr[1] == 'sl') {
                app.shortUrlToLong(paramArr[0], (res) => {
                    tid = res.tId
                    channel = res.channel
                    utm_source = res.utm_source || ''
                    utm_share = res.utm_share || ''
                    utm_medium = res.utm_medium || ''
                    utm_campaign = res.utm_campaign || ''
                })
            } else {
                tid = paramArr[0]
                channel = paramArr[1]
            }
        } else {
            channel = options.channel || 'wx_xcx'
            tid = options.tId
            utm_source = options.utm_source || ''
            utm_share = options.utm_share || ''
            utm_medium = options.utm_medium || ''
            utm_campaign = options.utm_campaign || ''
        }

        let shareUploadParams = {
            utm_source: utm_source,
            utm_share: utm_share,
            utm_medium: utm_medium,
            utm_campaign: utm_campaign,
        }

        this.setData({
            tId: tid,
            channel: channel,
            entrenceTime: dateFormat('yyyy-MM-dd hh:mm:ss:S'),
            utm_source: utm_source,
            utm_share: utm_share,
            utm_medium: utm_medium,
            utm_campaign: utm_campaign,
        })

        this.getActivityDetail(tid);
        this.shareUpload(shareUploadParams)

        // 埋点上报
        let uploadParam = {
            cur_page_id: 'OFGoodsFlowGoodsSetViewController',
            cur_page_entrance_time: dateFormat('yyyy-MM-dd hh:mm:ss:S'),
            cur_page_entrence_type: 1,
            ref_page_id: options.ref_page_id || null,
            opt_resource_area: 19,
            opt_resource_area_index: options.opt_resource_area_index || null,
            opt_resource_type: options.opt_resource_type || null,
            opt_resource_id: options.opt_resource_id || null,
            ref_page_resource_id: options.ref_page_resource_id || null,
            ref_opt_resource_id: options.ref_opt_resource_id || null,
            ref_opt_resource_type: options.ref_opt_resource_type || null,
            ref_opt_protocol: options.ref_opt_protocol || null,
            ref_write_sever_timestamp: options.ref_write_sever_timestamp || null,
            log_type: options.log_type || null,
        }

        logUpload.handleUpload(uploadParam);
    },
    getActivityDetail: function (tId) {
        const self = this;
        const { winH } = self.data;

        wx.showLoading({
            title: '数据请求中',
        })
        app.request({
            url: requestApi.getCollectionInfo,
            login: false,
            data: {
                collection_id: tId,
            },
        }, (res) => {
            if (res.original.ret_code == 200) {
                const collection_list = res.original.data.collection_list;
                const total = res.original.data.total;
                let info = null, nav = null, lists = { 0: []}, cur = 0, scrollList = [], groupInfo = null;

                collection_list.forEach(item => {
                    item.forEach(itm => {
                        if (itm.type == 73) {
                            if (itm.data.topics_type == 15) {
                                let discount_time = '';
                                
                                if (itm.data.discount_type == 2) {
                                    let interval = setInterval(() => {
                                        discount_time = self.getRemainTime(itm.data.discount_text);
                                        itm.data.discount_text -= 1;
                                        
                                        self.setData({
                                            discount_time
                                        })

                                        if (itm.data.discount_text < 0) {
                                            clearInterval(interval)
                                        }
                                      }, 1000)
                                }
                            }
                            info = itm.data;

                            wx.setNavigationBarTitle({
                                title: info.topics_title
                            })
                        }

                        if (itm.type == 52) {
                            groupInfo = itm.data;
                        }

                        if (itm.type == 1431) {
                            nav = itm.data.storeys_list;

                            nav.forEach(item => {
                                lists[item.resource_storeys_id] = [];
                            })

                            // cur = nav[0].resource_storeys_id;
                            delete lists[0];
                        }

                        if (itm.type == 34) {
                            itm.data.product_cover_image.full_path = formatImage.cdnImage(itm.data.product_cover_image.path, formatImage.THUMBNAIL_M);
                            
                            lists[itm.data.resource_storeys_id].push(itm.data);
                        }
                    })
                });

                self.setData({
                    info,
                    nav,
                    goodsList: lists,
                    groupInfo,
                    cur
                });

                let navH = 0, navTop = 0;
                if(nav && nav.length) {
                    let query = wx.createSelectorQuery();
                    query.select('.activity-nav').boundingClientRect();

                    nav.forEach(item => {
                        query.select('#gid' + item.resource_storeys_id).boundingClientRect();
                    });

                    query.exec(function(res) {
                        res.forEach((item, k) => {
                            if (item.id == '') {
                                navTop = item.top;
                                navH = item.height;
                            } else {
                                scrollList.push({
                                    id: item.id.split('gid')[1],
                                    min: k == 1 ? 0 : scrollList[k - 2].max,
                                    max: k == 1 ? item.height : scrollList[k - 2].max * 1 + item.height * 1,
                                })
                            }
                        })

                        self.setData({
                            navTop,
                            scrollList,
                            h: winH - navH
                        })
                    });
                }

                self.setData({
                    h: winH - navH
                })
            }
        }, (error) => {
            wx.showModal({
                title: '提示',
                showCancel: false,
                content: error,
            })
        }, () => {
            wx.hideLoading();
        })
    },
    pageScroll(e) {
        const { scrollTop } = e.detail;
        const { scrollList, cur, isShowBackTop, winH } = this.data;
        let showBackTop = false;

        scrollList.some((v, k) => {
            if (v.min <= scrollTop && scrollTop < v.max) {
                if (cur != k) {
                    this.setData({
                        cur: k,
                    });
                }
            }
        });

        if (scrollTop >= winH) {
            showBackTop = true;
        } else {
            showBackTop = false;
        }

        if (isShowBackTop != showBackTop) {
            this.setData({
                isShowBackTop: showBackTop
            })
        }
    },
    jumpNav(e) {
        const { id, index } = e.currentTarget.dataset;
        let offsetLeft = e.currentTarget.offsetLeft

        this.setData({
            cur: index,
            nId: id,
            scrollLeft: offsetLeft - this.data.winW / 2 + 40
        });
    },
    goBackTop() {
        this.setData({
            scrollTop: 0
        })
    },
    // 时间格式化
    getRemainTime: function(duration) {
        if (duration < 0) return false;
				let str = '';
        let d =  Math.floor(duration / (24 * 60 * 60));
        let h = (Math.floor(duration % (24 * 60 * 60) / (60 * 60)) + '').padStart(2, '0');
        let m = (Math.floor(duration % (60 * 60) / 60) + '').padStart(2, '0');
        let s = (Math.floor(duration % 60) + '').padStart(2, '0');
    
				if(d > 0) {
					str = `${d}天 `;
				}

				str += `${h}:${m}:${s}`;
        return str;
    },
    // 分享埋点数据上报
    shareUpload: function(params) {
        app.request({
            url: requestApi.shareUploadLogUrl,
            method: 'POST',
            login: false,
            data: {
                utm_source: params.utm_source,
                utm_share: params.utm_share,
                utm_medium: params.utm_medium,
                utm_campaign: params.utm_campaign
            },
        }, (data) => {
            // console.log(data)
        }, (error) => {
            // console.log(error)
        })
    },
})
